<template>
  <div id="myQuillEditor">
    <div style="float: right; margin-top: 19px; margin-right:10px">
      <div v-if="saveVisible">
        <i class="el-icon-loading"></i>保存中
      </div>
      <!-- <div v-else><i class="el-icon-check"></i>保存完成</div> -->
    </div>
    <quill-editor v-model="content" ref="myTextEditor" :options="editorOption" @blur="save()"></quill-editor>
    <el-upload
      style="display:none"
      class="avatar-uploader"
      :http-request="uploadImage"
      :action="uploadUrl"
      accept="image/jpeg, image/png, image/jpg"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      ref="upload"
    >
      <button type="button" id="uploadImg"></button>
    </el-upload>
    <div :visible.sync="videoUploadTag">
      <el-dialog
        width="50%"
        id="video_upload"
        style="margin-top: 1px"
        title="视频上传"
        :visible.sync="videoUploadTag"
        append-to-body
      >
        <el-tabs value="first">
          <el-tab-pane label="添加视频链接" name="first">
            <el-form>
              <el-form-item>
                <el-input v-model="videoLink" placeholder="请输入视频链接" clearable></el-input>
              </el-form-item>
              <el-form-item label="选择视频大小">
                <el-radio-group v-model="radio">
                  <el-radio label="big">大</el-radio>
                  <el-radio label="middle">中</el-radio>
                  <el-radio label="small">小</el-radio>
                  <el-radio label="self">自定义</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="radio=='self'">
                <el-col :xs="11" :md="6">
                  <el-input v-model="width_" type="number" placeholder="请输入宽度"></el-input>
                </el-col>
                <el-col :xs="11" :md="6" style="margin-left:10px">
                  <el-input v-model="height_" type="number" placeholder="请输入高度"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  size="small"
                  style="float:right"
                  @click="addVideoLink()"
                >添加</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import * as Quill from "quill"; // 引入编辑器
import ImageResize from "quill-image-resize-module";
import { ImageDrop } from "quill-image-drop-module";
Quill.register("modules/imageResize", ImageResize);
Quill.register("modules/imageDrop", ImageDrop);

const toolbar = [
  ["bold", "italic", "underline", "strike"],
  ["blockquote", "code-block"],
  [{ header: 1 }, { header: 2 }],
  [{ list: "ordered" }, { list: "bullet" }],
  [{ script: "sub" }, { script: "super" }],
  [{ indent: "-1" }, { indent: "+1" }],
  [{ direction: "rtl" }],
  [{ size: ["small", false, "large", "huge"] }],
  [{ header: [1, 2, 3, 4, 5, 6, false] }],
  [{ font: [] }],
  [{ color: [] }, { background: [] }],
  [{ align: [] }],
  ["link", "image", "video"]
];

export default {
  props: {
    value: {
      type: String,
      default: ""
    },
    /*上传图片的地址*/
    uploadUrl: {
      type: String,
      default: "/"
    },
    /*上传图片的file控件name*/
    fileName: {
      type: String,
      required: true
    },
    maxUploadSize: {
      type: Number,
      default: 5
    },
    auth: {
      type: Object
    }
  },
  data() {
    var self = this;
    return {
      radio: "middle",
      saveVisible: false,
      saveFlag: true,
      width_: "",
      height_: "",
      content: this.value,
      editorOption: {
        placeholder: "write something ...",
        modules: {
          toolbar: {
            container: toolbar,
            handlers: {
              image: function() {
                document.querySelector("#uploadImg").click();
              },
              video: function() {
                self.videoUploadTag = true;
              }
            }
          },
          imageDrop: true,
          imageResize: {
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white"
            },
            modules: ["Resize", "DisplaySize", "Toolbar"]
          }
        },
        theme: "snow"
      },
      videoUploadTag: false,
      //弹框插入的视频链接记录
      videoLink: "",
      imgUrIs: []
    };
  },
  methods: {
    beforeAvatarUpload(file) {
      const isLtSize = file.size < this.maxUploadSize * 1024 * 1024;
      if (!isLtSize) {
        this.$message.error(
          "上传头像图片大小不能超过 " + this.maxUploadSize + "MB!"
        );
      }
      return isLtSize;
    },
    uploadImage(content) {
      const params = new FormData();
      params.append(this.fileName, content.file);
      params.append("contentId", this.$store.state.res.id);

      this.$axios({
        method: "post",
        url: content.action,
        timeout: 1000 * 120,
        data: params,
        headers: {
          "ESENSE-DATA-SIGNATURE": "OK",
          "Content-Type": "multipart/form-data",
          Authorization: this.auth.Authorization
        }
      }).then(res => {
        if (res.data.code == 200) {
          let quill = this.$refs.myTextEditor.quill;
          let length = quill.getSelection().index;
          this.imgUrIs.push(res.data.data);
          this.editor.insertEmbed(length, "image", res.data.data);
          quill.setSelection(length + 1);
        }
      });
    },
    addVideoLink() {
      if (this.videoLink.length == 0) {
        alert("请输入视频链接");
      }
      var range = this.editor.getSelection();
      var index = 0;
      if (range == null) {
        index = 1;
      } else {
        index = range.index;
      }

      this.videoUploadTag = false;
      switch (this.radio) {
        case "middle":
          this.width_ = 500;
          this.height_ = 280;
          break;
        case "big":
          this.width_ = 700;
          this.height_ = 400;
          break;
      }
      if (this.width_ == "" || this.width_ == null) this.width_ = 280;
      if (this.height_ == "" || this.height_ == null) this.height_ = 160;
      this.width_ = this.width_ + "px";
      this.height_ = this.height_ + "px";
      let detail = {
        ops: [
          {
            insert: { video: this.videoLink },
            attributes: { width: this.width_, height: this.height_ }
          }
        ]
      };
      let indexDetail = {
        ops: [
          { retain: index },
          {
            insert: { video: this.videoLink },
            attributes: { width: this.width_, height: this.height_ }
          }
        ]
      };
      if (index > 0) {
        this.editor.updateContents(indexDetail);
      } else {
        this.editor.setContents(detail);
      }
    },
    save() {
      if (this.saveFlag == true) {
        this.saveFlag = false;
        this.saveVisible = true;
        this.deleteRepeatImage();
        this.$axios
          .post(
            this.$const.domain + "/v1/content/createContentHtml",
            {
              contentId: this.$store.state.res.id,
              value: this.content
            },
            {
              headers: { Authorization: this.auth.Authorization }
            }
          )
          .catch(error => {
            console.log(error);
            this.$message.error("网络错误，不能访问");
          });
        setTimeout(() => {
          this.saveFlag = true;
          this.saveVisible = false;
        }, 4000);
      }
    },
    deleteRepeatImage() {
      let delImgUrIs = [];
      this.imgUrIs.forEach(uri => delImgUrIs.push(uri));
      var node = document.getElementsByClassName("ql-editor")[0];
      var imgs = node.getElementsByTagName("img");

      for (let index = 0; index < imgs.length; index++) {
        let count = delImgUrIs.indexOf(imgs[index].currentSrc);
        if (count > -1) {
          delImgUrIs.splice(count, 1);
        }
      }
      this.$axios
        .post(
          this.$const.domain + "/v1/file/repeatImage",
          {
            imgUrIs: delImgUrIs,
            contentId: this.$route.params.id
          },
          {
            headers: { Authorization: this.auth.Authorization }
          }
        )
        .catch(error => {
          console.log(error);
        });
    }
  },
  computed: {
    editor() {
      return this.$refs.myTextEditor.quill;
    }
  },
  watch: {
    value(newVal) {
      if (this.editor) {
        if (newVal !== this.content) {
          this.content = newVal;
        }
      }
    },
    "$route.params.id"(newVal) {
      this.$axios
        .get(
          this.$const.domain + "/v1/file/getContentHtml?contentId=" + newVal,
          {
            headers: { Authorization: this.auth.Authorization }
          }
        )
        .then(res => {
          var node = document.getElementsByClassName("ql-editor")[0];
          node.innerHTML = res.data;
        })
        // eslint-disable-next-line no-unused-vars
        .catch(error => {
          var node = document.getElementsByClassName("ql-editor")[0];
          node.innerHTML = "";
        });
    }
  },
  mounted() {
    this.$axios
      .get(
        this.$const.domain +
          "/v1/file/getContentHtml?contentId=" +
          this.$route.params.id,
        {
          headers: { Authorization: this.auth.Authorization }
        }
      )
      .then(res => {
        var node = document.getElementsByClassName("ql-editor")[0];
        node.innerHTML = res.data;
      })
      .catch(error => {
        console.log(error);
      });
  }
};
</script>

<style>
.ql-editor {
  min-height: 20vh !important;
}
</style>